package main.java.com.lee.atomic;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2021/12/27
 */
public class AtomicStampedReferenceTest {
    public static void main(String[] args) throws InterruptedException {
        Integer i = 1;
        AtomicStampedReference<Integer> reference = new AtomicStampedReference<>(i, 0);
        Thread t1 = new Thread(()->{
            int stamp = reference.getStamp();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean compareAndSet = reference.compareAndSet(i, 2, stamp, stamp + 1);
            if (!compareAndSet) {
                System.out.println("t1失败");
            }
        });

        Thread t2 = new Thread(()->{
            int stamp = reference.getStamp();
            int b=3;
            boolean compareAndSet1 = reference.compareAndSet(i, b, stamp, stamp + 1);
            boolean compareAndSet2 = reference.compareAndSet(b, i, stamp+1, stamp + 2);
            System.out.println("t2执行结束后的i值: "+i);
            if (!compareAndSet1 || !compareAndSet2) {
                System.out.println("t2失败");
            }
        });


        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(i);

    }
}
